package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    // 地址列表
    @Override
    public List<Address> findList() {
        // 1.构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId()); // 用户id
        // 2.查询并返回
        return addressMapper.selectList(qw);
    }


    // 新增地址
    @Override
    public void save(Address address) {
        // 1.补全信息
        address.setUserId(UserHolder.get().getId()); // 用户id
        address.setIsDefault(0); // 非默认地址

        // 2.mapper新增
        addressMapper.insert(address);
    }


    // 设为默认地址
    @Override
    public void setDefault(Long id) {
        // 1.把当前用户下所有收货地址设置为非默认
        // 1-1 设置修改内容
        Address address1 = new Address();
        address1.setIsDefault(0);
        // 1-2 设置用户id为条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        // 1-3 更新
        addressMapper.update(address1, qw);

        // 2.将当前收货地址设置为默认
        Address address2 = new Address();
        address2.setId(id);// 收货地址id
        address2.setIsDefault(1); // 默认
        addressMapper.updateById(address2);
    }

    // 去结算（查询默认收货地址)
    @Override
    public Address findDefault() {
        // 1.构建 条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault, 1); // 默认值 = 1
        qw.eq(Address::getUserId, UserHolder.get().getId()); // 用户id

        // 2.调用mapper查并返回
        return addressMapper.selectOne(qw);
    }

    // 回显地址
    @Override
    public Address findById(Long id) {
        // 1.先查菜品
        Address address = addressMapper.selectById(id);
        // 2.根据菜品id查询口味
        // 2-1 构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, id);
        // 2-2  调用mapper
        List<Address> addressList = addressMapper.selectList(qw);
        //  4.返回菜品
        return address;
    }


    //修改地址
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    //删除地址
    @Override
    public void delete(Long ids) {
        addressMapper.deleteById(ids);
    }
}
